<?php
/**
 * Created by andrei
 * Date: 9/19/12
 * Time: 11:43 AM
 */
require_once('TemplateConf.php');
require_once('LayoutItemConf.php');
require_once('ImageConf.php');
require_once('TextConf.php');
require_once('DesignConf.php');
require_once('ProductConf.php');
require_once('PageConf.php');
require_once('ApplicationConf.php');
require_once('GalleryConf.php');
require_once('GalleryImageConf.php');
require_once('PoemConf.php');
require_once('SizeConf.php');

 class ProductsFlashManager extends Engine {

	public function __construct ()
    {

		$this->galleryObj = new Db_Products_PhotosGalleries();
		$this->photosObj =  new Db_Products_Photos();
		$this->templateObj = new Db_Products_Templates();
		$this->designObj = new Db_Products_Designs();
		$this->textsObj = new Db_Products_ProductPageTexts();
		$this->imagesObj = new Db_Products_ProductPageImages();
		$this->layoutItemsObj = new Db_Products_LayoutItems();
		$this->designTextsObj = new Db_Products_DesignTexts();
		$this->designImagesObj = new Db_Products_DesignImages();
		$this->productsPages = new Db_Products_ProductPages();
		$this->productsObj = new Db_Products_Products();
		$this->themesObj = new Db_Products_Themes();
		$this->sizesObj = new Db_Products_Sizes();
		$this->textColorObj = new Db_Products_ProductPageTextColor();

		$this->memoryProductsPagesObj = new Db_Products_MemoryListProductPages();
		$this->memoryTextsObj = new Db_Products_MemoryListProductPageTexts();
		$this->memoryImagesObj = new Db_Products_MemoryListProductPageImages();
		$this->memoryListObj = new Db_Products_MemoryList();
		$this->memoryListProductsObj = new Db_Products_MemoryListProducts();

	}

	 public function getFonts() {
		 $dir = opendir(PRODUCTS_FONTS_PATH);
		 $arr = array();
 		//List files in images directory
		 while (($file = readdir($dir)) !== false) {
			 if ($file != "." && $file != "..") {
				 $tArray = explode(".", $file);
				 $fontName = $tArray[0];
				 $arr[] = $fontName;
			 }
		 }

		 closedir($dir);
		 return $arr;
	 }

	 /**
	  * @param $productId
	  * @param string $memoryProductId
	  * @param $memoryIdentifier
	  * @param $allTemplates
	  * @internal param $isMemoryProductId
	  * @return ApplicationConf|string
	  */
	 public function getData($productId, $memoryProductId = '', $memoryIdentifier, $allTemplates) {
		 $applicationConfig = new ApplicationConf();
		 $productId = Utils::memoryProductIdDecode($productId);
		 $isMemoryProductId = false;

		 if(!empty($memoryProductId)) {
			 $memoryProductId = Utils::memoryProductIdDecode($memoryProductId);
			 $isMemoryProductId = true;
		 }

		$dataProduct = false;
		if ($isMemoryProductId) {
			//$dataProductId = $this->memoryListProductsObj->findById($productId);
		 	$dataProduct = $this->memoryListProductsObj->getProductDataByMemoryListProductId($memoryProductId, $productId, $memoryIdentifier);
		}

		if (!$dataProduct) {
			$isMemoryProductId = false;
			$dataProduct = $this->productsObj->getProductDataByProductId($productId);
		}

		$productConfigObj = new ProductConf();
//		$pageConfig = new PageConf();
//		$templateConfig = new TemplateConf();
//		$textObj = new TextConf();
//		$imageObj = new ImageConf();
		//return print_r($dataProduct,true);

		if($dataProduct[$productId]) {
			$productDates = $dataProduct[$productId];

			$productConfigObj = new ProductConf();
			$productConfigObj->id = $productId;
			$productConfigObj->p_photo_gallery_id = $productDates['p_photo_gallery_id'];
			$productConfigObj->p_type = $productDates['p_type'];
			$productConfigObj->p_cover_type_id = $productDates['p_cover_type_id'];
			$productConfigObj->p_name = $productDates['p_name'];
			$productConfigObj->p_theme_id = ($isMemoryProductId) ? $productDates['p_theme_id'] : $productDates['p_theme_is_default'];
			$productConfigObj->is_memory_product_id = ($isMemoryProductId) ? true : false;
			$productConfigObj->p_fonts = unserialize($productDates['p_fonts']);

			if ($memoryProductId) {
				$productConfigObj->p_names = $this->memoryListProductsObj->getMemoryProductNames($memoryProductId);
			}

			$sizeConfigObj = new SizeConf();
			$sizeConfigObj->id = $productDates['s_size_id'];
			$sizeConfigObj->s_width = $productDates['s_width'];
			$sizeConfigObj->s_height = $productDates['s_height'];
			$sizeConfigObj->s_name = $productDates['s_name'];
			$sizeConfigObj->s_face_number = $productDates['s_face_number'];
			$sizeConfigObj->s_orientation = $productDates['s_orientation'];
			$productConfigObj->p_size = $sizeConfigObj;


			if(isset($productDates['pages']) && $productDates['pages']) {
				foreach ($productDates['pages'] as $pageId=>$pageDates) {
					$pageConfig = new PageConf();
					$pageConfig->id = $pageId;
					$pageConfig->pp_product_id = $productId;
					$pageConfig->pp_template_id = $pageDates['pp_template_id'];
					$pageConfig->pp_page_index = $pageDates['pp_page_index'];
					$templateConfig = new TemplateConf();

					if($pageDates['items']) {

						foreach ($pageDates['items'] as $itemId=>$templateDates) {

							$templateConfig->id = $templateDates->template_id;
							$templateConfig->t_size_id = $templateDates->t_size_id;
							$templateConfig->t_name = $templateDates->t_name;

							$imageObj = new ImageConf();
							$textObj = new TextConf();

							$imageObj->li_id = $textObj->li_id = $itemId;
							$imageObj->li_owner_id = $textObj->li_owner_id = $templateDates->template_id;
							$imageObj->li_owned_by = $textObj->li_owned_by = $templateDates->li_owned_by;
							$imageObj->li_type = $textObj->li_type = $templateDates->li_type;
							$imageObj->li_level = $textObj->li_level = $templateDates->li_level;

							$imageObj->li_design_layer = $textObj->li_design_layer = $templateDates->li_design_layer;

							if($templateDates->li_type == 'text') {
								$textObj->li_rotation = ($isMemoryProductId && $templateDates->mppt_rotation) ? $templateDates->mppt_rotation : $templateDates->li_rotation;
								$textObj->li_width = ($isMemoryProductId && $templateDates->mppt_width) ? $templateDates->mppt_width : $templateDates->li_width;
								$textObj->li_height = ($isMemoryProductId && $templateDates->mppt_height) ? $templateDates->mppt_height : $templateDates->li_height;
								$textObj->li_x = ($isMemoryProductId && $templateDates->mppt_x) ? $templateDates->mppt_x : $templateDates->li_x;
								$textObj->li_y = ($isMemoryProductId && $templateDates->mppt_y) ? $templateDates->mppt_y : $templateDates->li_y;
								$textObj->li_is_poem = $templateDates->li_is_poem;
								$textObj->li_is_multi_value= $templateDates->li_is_multi_value;

								$textObj->ppt_product_page_id = ($isMemoryProductId)? $templateDates->mppt_memory_product_page_id : $templateDates->ppt_product_page_id;
								$textObj->ppt_layout_item_id = $itemId;
								$textObj->ppt_text = ($isMemoryProductId) ? $templateDates->mppt_text : $templateDates->ppt_text;
								$textObj->ppt_font_family = ($isMemoryProductId) ? $templateDates->mppt_font_family : $templateDates->ppt_font_family;
								$textObj->ppt_font_size = ($isMemoryProductId) ? $templateDates->mppt_font_size : $templateDates->ppt_font_size;
								$textObj->ppt_text_align = ($isMemoryProductId) ? $templateDates->mppt_text_align : $templateDates->ppt_text_align;
								$textObj->ppt_vertical_align = ($isMemoryProductId) ? $templateDates->mppt_vertical_align : $templateDates->ppt_vertical_align;
								$textObj->ppt_color = ($isMemoryProductId) ? $templateDates->mppt_color : $templateDates->ppt_color;
								$textObj->ppt_poem_id = ($isMemoryProductId) ? $templateDates->mppt_poem_id : 0;
//									if($isMemoryProductId) {
//										$textObj->ppt_rotation = $templateDates->mppt_rotation;
//										$textObj->ppt_width = $templateDates->mppt_width;
//										$textObj->ppt_height = $templateDates->mppt_height;
//										$textObj->ppt_x = $templateDates->mppt_x;
//										$textObj->ppt_y = $templateDates->mppt_y;
//									}
								$templateConfig->texts[] = $textObj;

							} elseif($templateDates->li_type == 'image') {

								$imageObj->li_rotation = ($isMemoryProductId && $templateDates->mppi_rotation) ? $templateDates->mppi_rotation : $templateDates->li_rotation;
								$imageObj->li_width = ($isMemoryProductId && $templateDates->mppi_width) ? $templateDates->mppi_width : $templateDates->li_width;
								$imageObj->li_height = ($isMemoryProductId && $templateDates->mppi_height) ? $templateDates->mppi_height : $templateDates->li_height;
								$imageObj->li_x = ($isMemoryProductId && $templateDates->mppi_x) ? $templateDates->mppi_x : $templateDates->li_x;
								$imageObj->li_y = ($isMemoryProductId && $templateDates->mppi_y) ? $templateDates->mppi_y : $templateDates->li_y;
								$imageObj->li_is_multi_value= $imageObj->li_is_multi_value;

								$imageObj->ppi_product_page_id = ($isMemoryProductId == true ? $templateDates->mppi_memory_product_page_id : $templateDates->ppi_product_page_id);
								$imageObj->ppi_layout_item_id = $itemId;
								$imageObj->ppi_photo_id = ($isMemoryProductId) ? $templateDates->mppi_photo_id : $templateDates->ppi_photo_id;
								$imageObj->ppi_iw = ($isMemoryProductId) ? $templateDates->mppi_iw : $templateDates->ppi_iw;
								$imageObj->ppi_ih = ($isMemoryProductId) ? $templateDates->mppi_ih : $templateDates->ppi_ih;
								$imageObj->ppi_ir = ($isMemoryProductId) ? $templateDates->mppi_ir : $templateDates->ppi_ir;
								$imageObj->ppi_ix = ($isMemoryProductId) ? $templateDates->mppi_ix : $templateDates->ppi_ix;
								$imageObj->ppi_iy = ($isMemoryProductId) ? $templateDates->mppi_iy : $templateDates->ppi_iy;
								$imageObj->ppi_image_filter = ($isMemoryProductId) ? $templateDates->mppi_image_filter : $templateDates->ppi_image_filter;
//									if($isMemoryProductId) {
//										$imageObj->ppi_rotation = $templateDates->mppi_rotation;
//										$imageObj->ppi_width = $templateDates->mppi_width;
//										$imageObj->ppi_height = $templateDates->mppi_height;
//										$imageObj->ppi_x = $templateDates->mppi_x;
//										$imageObj->ppi_y = $templateDates->mppi_y;
//									}
								$templateConfig->images[] = $imageObj;
							}

						}
					}
					$pageConfig->pp_template_config = $templateConfig;
					$productConfigObj->pages[] = $pageConfig;
				}
			}
		} else {
			return "Error: no data product";
		}

		$productConfigObj->poems = $this->getPoemsByProductId($productId);
		$applicationConfig->product_config = $productConfigObj;

		$applicationConfig->themes = $this->themesObj->getThemesByProductId($productId);
		$applicationConfig->templates = $this->getFlashTemplates($productDates['s_size_id'], $allTemplates, $productId);
		// return $applicationConfig->templates;

		 /* return designs strict for used templates in Frontend or all designs in Backend */
		//$applicationConfig->designs = (empty($memoryIdentifier) ? $this->getDesigns() : $this->getDesigns($productConfigObj->p_size_id, $productId));
		$applicationConfig->designs = $this->getDesigns($productDates['s_size_id'], $productId);
		$galleryConfigObject = new GalleryConf();
		$gallery  = (!empty($memoryIdentifier) ? $this->memoryListObj->findByField('ml_memory_identifier', $memoryIdentifier) : null);
		$galleryConfigObject->id = (isset($gallery->ml_gallery_id) ? $gallery->ml_gallery_id : $productConfigObj->p_photo_gallery_id );

		$allImagesGallery = $this->galleryObj->getGalleryImagesById($galleryConfigObject->id);

		if(is_array($allImagesGallery)) {
			foreach($allImagesGallery as $photoId => $image) {
				$galleryImageConfigObj = new GalleryImageConf();
				$galleryImageConfigObj->id = $photoId;
				$galleryImageConfigObj->ph_gallery_id = $image->ph_gallery_id;
				$galleryImageConfigObj->ph_original = $image->ph_original;
				$galleryImageConfigObj->ph_ow = $image->ph_ow;
				$galleryImageConfigObj->ph_oh = $image->ph_oh;
				$galleryImageConfigObj->ph_resized = $image->ph_resized;
				$galleryImageConfigObj->ph_rw = $image->ph_rw;
				$galleryImageConfigObj->ph_rh = $image->ph_rh;

				$galleryConfigObject->images[$applicationConfig->arrayKeysPrefix.$photoId] = $galleryImageConfigObj;
			}
		}
		 /* return strict images used in designs  */
		 $applicationConfig->designsImages = $this->getDesignsImages($applicationConfig->designs);
		 $applicationConfig->gallery_config = $galleryConfigObject;
		 $applicationConfig->urlFonts = self::$PROJECT['pr_resources_'.conf('ENVIRONMENT')] . str_replace(PUBLIC_RESOURCES_PATH, '', PRODUCTS_FONTS_PATH);
		return $applicationConfig;
	}

	 public function getPoemsByProductId($productId) {
		 $poems = Db_Products_Poems::getPoemsByProductId($productId);
		 $poemsReturn = array();
		 if ($poems) {
			 foreach ($poems as $poem) {
				 $poemConfig = new PoemConf();
				 $poemConfig->id = $poem['poem_id'];
				 $poemConfig->title = t(T_POEMS_TITLE, $poem['pe_title']);
				 $poemConfig->text = t(T_POEMS_TITLE, $poem['pe_content']);
				 $poemsReturn[] = $poemConfig;
			 }
		 }
		 return $poemsReturn;
	 }

	 /**
	  * @param $productConfiguration
	  * @param $isFrontEnd
	  * @param $memoryListProductId
	  * @param $memoryIdentifier
	  * @return mixed
	  */
	 public function saveProduct($productConfiguration, $isFrontEnd, $memoryListProductId, $memoryIdentifier) {
		$memoryListProductIdFun = $memoryListProductId;
		 $memoryListProductId = ($memoryListProductId) ? Utils::memoryProductIdDecode($memoryListProductId) : null;

		if(isset($productConfiguration->pages)) {
			if(!$isFrontEnd && !$memoryListProductId) {
				$this->productsPages->deleteByField('pp_product_id',$productConfiguration->id, 0);
			} else {
				$this->memoryProductsPagesObj->deleteByField('mpp_memory_product_id', $memoryListProductId, 0);
			}

			if($isFrontEnd){
				$timeNow = time();

				$this->memoryListObj->id = null;
				$this->memoryListObj->ml_memory_identifier = $memoryIdentifier;
				$this->memoryListObj->ml_project_id = self::$PROJECT['id'];
				$this->memoryListObj->save(true);
				$memoryId = $this->memoryListObj->id;
				$mlpName = null;
				$version = null;

				if(!$memoryListProductId) {
					$memoryListProductIdPersonalized = $this->memoryListProductsObj->checkIsPersonalized($productConfiguration->id, $productConfiguration->p_theme_id);

					if (isset($memoryListProductIdPersonalized) && !isset($memoryListProductIdPersonalized['mpp_memory_product_id'])) {
						$memoryListProductId = $memoryListProductIdPersonalized['mlp_id'];
					} else {
						$getVersion = $this->memoryListProductsObj->findByField('mlp_product_id', $productConfiguration->id, 'deleted', 'id DESC');
						$version = (isset($getVersion) ? (int)$getVersion->mlp_version + 1 : null );
						$mlpName = 'Version '.$version .' ' . date('H:i',$timeNow). ' | ' . Utils::formatDateUser($timeNow,false);
					}

				}
				$memoryListProductId = (isset($memoryListProductId) && $memoryListProductId != 0 ? $memoryListProductId : null);

				$this->memoryListProductsObj->id = $memoryListProductId;
				$this->memoryListProductsObj->mlp_memory_id = $memoryId;
				$this->memoryListProductsObj->mlp_product_id = $productConfiguration->id;
				$this->memoryListProductsObj->mlp_theme_id = $productConfiguration->p_theme_id;
				if(!$memoryListProductId) {
					$this->memoryListProductsObj->mlp_date = Utils::formatDateDb($timeNow, true);
					$this->memoryListProductsObj->mlp_name = $mlpName;
					$this->memoryListProductsObj->mlp_version = $version;
				}
				$this->memoryListProductsObj->mlp_edited_by_user = 1;
				$this->memoryListProductsObj->mlp_personalization_date = Utils::formatDateDb(time(), true);
				if (!$this->memoryListProductsObj->save()){
					return false;
				}
			}

			//change default theme id
			if (!$isFrontEnd) {
				Db_Products_Products::updateDefaultTheme($productConfiguration->id, $productConfiguration->p_theme_id);
			}

			foreach ($productConfiguration->pages as $page) {
				 $this->savePage($page, $productConfiguration->id, $isFrontEnd, $memoryListProductIdFun, $memoryIdentifier, $this->memoryListProductsObj->id);
			}
			//save names
			$this->memoryListProductsObj->deleteNamesByMemoryProductId($this->memoryListProductsObj->id);
			if (isset($productConfiguration->p_names)) {
				$dataInsert = array();
				foreach ($productConfiguration->p_names as $name) {
					$dataInsert[] = array(
						'mn_memory_product_id' => $this->memoryListProductsObj->id,
						'mn_name' => $name
					);
				}
				self::$DB->insertBatch(TAB_MEMORY_LIST_PRODUCT_NAMES, $dataInsert);
			}

		}

		 if (!$isFrontEnd && !$memoryListProductId) {
			 $this->productsObj->id = $productConfiguration->id;
			 $this->productsObj->p_fonts = serialize($productConfiguration->p_fonts);
			 $this->productsObj->save();
		 }

		return (!$isFrontEnd && !$memoryListProductId)? $productConfiguration->id : Utils::memoryProductIdEncode($this->memoryListProductsObj->id);
	}

	 /**
	  * @param $page
	  * @param $productId
	  * @param bool $isFrontEnd
	  * @param int $memoryListProductIdFun
	  * @param string $memoryIdentifier
	  * @param $newMemoryListProductId
	  * @return mixed
	  */
	 public function savePage($page, $productId, $isFrontEnd = false, $memoryListProductIdFun = 0, $memoryIdentifier = null, $newMemoryListProductId) {
		if(!$isFrontEnd && !$memoryListProductIdFun) {
			$this->productsPages->id = null;
			$this->productsPages->pp_product_id = $productId;
			$templateConfiguration = $page->pp_template_config;
			$this->productsPages->pp_template_id = $templateConfiguration->id;
			$this->productsPages->pp_page_index = $page->pp_page_index;
			$this->productsPages->save();
			$this->savePrivateTemplate($templateConfiguration,$this->productsPages->id);
		} else {

			$this->memoryProductsPagesObj->id = null;
			$this->memoryProductsPagesObj->mpp_memory_product_id = $newMemoryListProductId;
			$templateConfiguration = $page->pp_template_config;
			$this->memoryProductsPagesObj->mpp_template_id = $templateConfiguration->id;
			$this->memoryProductsPagesObj->mpp_page_index = $page->pp_page_index;
			$this->memoryProductsPagesObj->save();
			$this->savePrivateTemplate($templateConfiguration, $this->memoryProductsPagesObj->id, $isFrontEnd, $memoryListProductIdFun);

		}
	}

	 /**
	  * @param $sizeId
	  * @param $allTemplates
	  * @return array
	  */
	 public function getTemplates($sizeId, $allTemplates) {
		return $this->getFlashTemplates($sizeId, $allTemplates);
	}

	 /**
	  * @param $sizeId
	  * @param $allTemplates
	  * @param int $productId
	  * @return array
	  */
	 public function getFlashTemplates($sizeId, $allTemplates, $productId = 0) {
		$templatesList = $this->templateObj->getTemplatesBySizeId($sizeId, $allTemplates, $productId);
		 //return $templatesList;
		$dataReturn = array();

		foreach ($templatesList as $templateId=>$template) {
			$templateObject = new TemplateConf();
			$templateObject->id = $templateId;
			$templateObject->t_name = $template['t_name'];
			$templateObject->t_size_id = $template['t_size_id'];
			foreach($template['items'] as $item) {

				if($item->li_type == 'text') {
					$textObject = new TextConf();
					$textObject->li_id = $item->li_id;
					$textObject->li_owner_id = $item->li_owner_id;
					$textObject->li_owned_by = 'template';
					$textObject->li_type = 'text';
					$textObject->li_level = $item->li_level;
					$textObject->li_rotation = $item->li_rotation;
					$textObject->li_width = $item->li_width;
					$textObject->li_height = $item->li_height;
					$textObject->li_x = $item->li_x;
					$textObject->li_y = $item->li_y;
					$textObject->li_is_poem = $item->li_is_poem;

					$templateObject->texts[] = $textObject;

				} elseif($item->li_type == 'image') {
					$imageObject = new ImageConf();
					$imageObject->li_id = $item->li_id;
					$imageObject->li_owner_id = $item->li_owner_id;
					$imageObject->li_owned_by = 'template';
					$imageObject->li_type = 'image';
					$imageObject->li_level = $item->li_level;
					$imageObject->li_rotation = $item->li_rotation;
					$imageObject->li_width = $item->li_width;
					$imageObject->li_height = $item->li_height;
					$imageObject->li_x = $item->li_x;
					$imageObject->li_y = $item->li_y;

					$templateObject->images[] = $imageObject;
				}
			}


			$dataReturn[] = $templateObject;
		}
		return $dataReturn;

	}

	 /**
	  * @return mixed
	  */
	 public function getThemes() {
		return $this->themesObj->getThemesByProductId();
	}

	 public function getDesignsByTemplates($templates) {

	 }

	 /**
	  * @param null $sizeId
	  * @param int $productId
	  * @return array
	  */
	 public function getDesigns($sizeId = null, $productId = 0){
		$designsList = $this->designObj->getDesigns($sizeId, $productId);
		$dataDesignsReturn = array();
		$applicationConfigObj = new ApplicationConf();
		$pageTextsColor = $this->textColorObj->getAllProductPageTextColor();
		if(count($designsList) > 0 ) {
			foreach($designsList as $themeId => $valueTemplate) {
				foreach ($valueTemplate as $templateId => $designs) {
					foreach($designs as $designId => $value) {
						$designObject = new DesignConf();
						$designObject->id = $designId;
						$designObject->d_template_id = $templateId;
						$designObject->d_theme_id = $themeId;
						$designObject->d_name = $value['d_name'];

						if(isset($pageTextsColor[$designId])) {
							foreach($pageTextsColor[$designId] as $pageTextColor) {
								$textObject = new TextConf();
								$textObject->ppt_color = (isset($pageTextColor['pptc_color']) ? $pageTextColor['pptc_color'] : '');
								$textObject->ppt_font_family = (isset($pageTextColor['pptc_font_family']) ? $pageTextColor['pptc_font_family'] : '');
								$textObject->ppt_font_size = (isset($pageTextColor['pptc_font_size']) ? $pageTextColor['pptc_font_size'] : '');
								$textObject->ppt_line_height = (isset($pageTextColor['pptc_line_height']) ? $pageTextColor['pptc_line_height'] : '');
								$textObject->ppt_product_page_id = (isset($pageTextColor['pptc_product_page_id']) ? $pageTextColor['pptc_product_page_id'] : '');
								$textObject->ppt_text = (isset($pageTextColor['pptc_text']) ? $pageTextColor['pptc_text'] : '');
								$textObject->ppt_text_align = (isset($pageTextColor['pptc_text_align']) ? $pageTextColor['pptc_text_align'] : '');
								$textObject->ppt_vertical_align = (isset($pageTextColor['pptc_vertical_align']) ? $pageTextColor['pptc_vertical_align'] : '');
								$textObject->li_id = (isset($pageTextColor['pptc_loyout_item_id']) ? $pageTextColor['pptc_loyout_item_id'] : '');
								$designObject->d_template_texts[] = $textObject;
							}
						}

						foreach($value['items'] as $item) {
							if($item->li_type == 'text') {
								$textObject = new TextConf();
								$textObject->li_id = $item->li_id;
								$textObject->li_owner_id = $item->design_id;
								$textObject->li_owned_by = $item->li_owned_by;
								$textObject->li_type = $item->li_type;
								$textObject->li_level = $item->li_level;
								$textObject->li_rotation = $item->li_rotation;
								$textObject->li_width = $item->li_width;
								$textObject->li_height = $item->li_height;
								$textObject->li_x = $item->li_x;
								$textObject->li_y = $item->li_y;
								$textObject->li_design_layer = $item->li_design_layer;
								$textObject->ppt_text = $item->dt_text;
								$textObject->ppt_font_family = $item->dt_font_family;
								$textObject->ppt_font_size = $item->dt_font_size;
								$textObject->ppt_text_align = $item->dt_text_align;
								$textObject->ppt_vertical_align = $item->dt_vertical_align;
								$textObject->ppt_color = $item->dt_color;
								$designObject->texts[] = $textObject;
							} else {
								$imageObject = new ImageConf();
								$imageObject->li_id = $item->li_id;
								$imageObject->li_owner_id = $item->design_id;
								$imageObject->li_owned_by = $item->li_owned_by;
								$imageObject->li_type = $item->li_type;
								$imageObject->li_level = $item->li_level;
								$imageObject->li_rotation = $item->li_rotation;
								$imageObject->li_width = $item->li_width;
								$imageObject->li_height = $item->li_height;
								$imageObject->li_x = $item->li_x;
								$imageObject->li_y = $item->li_y;
								$imageObject->li_design_layer = $item->li_design_layer;
								$imageObject->ppi_photo_id = $item->di_photo_id;
								$imageObject->ppi_iw = $item->di_iw;
								$imageObject->ppi_ih = $item->di_ih;
								$imageObject->ppi_ir = $item->di_ir;
								$imageObject->ppi_ix = $item->di_ix;
								$imageObject->ppi_iy = $item->di_iy;
								$imageObject->ppi_image_filter = $item->di_image_filter;
								$designObject->images[] = $imageObject;
							}
						}
						$dataDesignsReturn[$applicationConfigObj->arrayKeysPrefix.$templateId][$applicationConfigObj->arrayKeysPrefix.$themeId] = $designObject;
					}
				}
			}
		}

		return $dataDesignsReturn;
	}

	 /**
	  * Save Design from flash
	  * @param $designConfiguration
	  * @return string
	  */
	 public function saveDesign($designConfiguration) {
		if($this->designObj->checkDesignExists($designConfiguration->id,$designConfiguration->d_template_id,$designConfiguration->d_theme_id)) {
			return "Design with the same theme and template already exists !!!";
		}

		$this->designObj->id = (!$designConfiguration->id) ? null :$designConfiguration->id ;
		$this->designObj->d_theme_id = $designConfiguration->d_theme_id;
		$this->designObj->d_template_id = $designConfiguration->d_template_id;
		$this->designObj->d_name = $designConfiguration->d_name;
		$this->designObj->save();
		 //Save Design Layout products text color
		$this->saveDesignLayoutTextsColor($designConfiguration->d_template_texts, $this->designObj->id);
		$this->saveLayouts($designConfiguration, $this->designObj->id,'design');
		return $this->designObj->id;
	}

	 /**
	  * Save Template from flash
	  * @param $templateConfiguration
	  * @return mixed
	  */
	 public function saveTemplate($templateConfiguration) {
		return $this->savePrivateTemplate($templateConfiguration, 0, false, 0, true);
	}

	 /**
	  * @param $templateConfiguration
	  * @param int $productPageId
	  * @param bool $isFrontEnd
	  * @param int $memoryListProductId
	  * @param bool $onlyTemplate
	  * @return mixed
	  */
	 private function savePrivateTemplate($templateConfiguration, $productPageId = 0, $isFrontEnd = false, $memoryListProductId = 0, $onlyTemplate = false) {
		 $this->templateObj->id = $templateConfiguration->id;
		 $this->templateObj->t_name = $templateConfiguration->t_name;
		 $this->templateObj->t_size_id = $templateConfiguration->t_size_id;
		 if(!$isFrontEnd && !$memoryListProductId){
			$this->templateObj->save();
		}

		if($productPageId > 0) {
			 $templateConfiguration->ppi_product_page_id = $productPageId;
		}

	 	$this->saveLayouts($templateConfiguration, $this->templateObj->id, 'template', $isFrontEnd,$memoryListProductId,$onlyTemplate);
		return $this->templateObj->id;
	}

	 /**
	  * @param $objConfiguration
	  * @param $id
	  * @param string $type
	  * @param bool $isFrontEnd
	  * @param int $memoryListProductId
	  * @param bool $onlyTemplate
	  * @return mixed
	  */
	 public function saveLayouts($objConfiguration, $id, $type='template', $isFrontEnd = false, $memoryListProductId = 0, $onlyTemplate = false) {
		$textsObjects = $objConfiguration->texts;
		$imagesObjects = $objConfiguration->images;
		$layouts = array();

		if(!$isFrontEnd && !$memoryListProductId) {
			//$this->layoutItemsObj->deleteByOwner($id, $type);
			foreach($textsObjects as $text) {
				$layouts[$text->li_id] = $text->li_id;
			}
			foreach($imagesObjects as $images) {
				$layouts[$images->li_id] = $images->li_id;
			}

			$this->layoutItemsObj->deleteByFieldsNotInArray(array(
			 'id' => $layouts,
			 'li_owner_id' => $id,
			 'li_owned_by' => $type
			));

		} else {
			$this->memoryTextsObj->deleteByField('mppt_memory_product_page_id', $objConfiguration->ppi_product_page_id);
			$this->memoryImagesObj->deleteByField('mppi_memory_product_page_id', $objConfiguration->ppi_product_page_id);
		}

		 if($textsObjects){
			foreach ($textsObjects as $textObj) {
					$textObj->ppt_product_page_id = (isset($objConfiguration->ppi_product_page_id) ? $objConfiguration->ppi_product_page_id : $textObj->ppt_product_page_id);

				if(!$objConfiguration->id) {
					$textObj->li_id = 0;
				}
				$this->saveItems($textObj, $id, 'text', $type, $isFrontEnd, $memoryListProductId, $onlyTemplate);
			}
		}
		if($imagesObjects) {
			foreach ($imagesObjects as $imageObj) {
					$imageObj->ppi_product_page_id = (isset($objConfiguration->ppi_product_page_id) ? $objConfiguration->ppi_product_page_id : $imageObj->ppi_product_page_id );

				if(!$objConfiguration->id) {
                    $imageObj->li_id = 0;
                }
				$this->saveItems($imageObj, $id, 'image', $type, $isFrontEnd, $memoryListProductId, $onlyTemplate);
			}
		}
	}

	 /**
	  * @param $obj
	  * @param $ownerId
	  * @param string $type
	  * @param string $owned
	  * @param bool $isFrontEnd
	  * @param int $memoryListProductId
	  * @param bool $onlyTemplate
	  * @return mixed
	  */
	 private function saveItems($obj, $ownerId, $type = 'text', $owned ='template', $isFrontEnd = false, $memoryListProductId=0, $onlyTemplate = false) {
		if(!$isFrontEnd && !$memoryListProductId) {
			$this->layoutItemsObj->id = (isset($obj->li_id) ? $obj->li_id : null);
			$this->layoutItemsObj->li_owner_id = $ownerId;
			$this->layoutItemsObj->li_owned_by = $owned;
			$this->layoutItemsObj->li_type = $type;
			$this->layoutItemsObj->li_level = $obj->li_level;
			$this->layoutItemsObj->li_rotation = $obj->li_rotation;
			$this->layoutItemsObj->li_width = $obj->li_width;
			$this->layoutItemsObj->li_height = $obj->li_height;
			$this->layoutItemsObj->li_x = $obj->li_x;
			$this->layoutItemsObj->li_y = $obj->li_y;
			$this->layoutItemsObj->li_design_layer = $obj->li_design_layer;
			$this->layoutItemsObj->li_is_multi_value = $obj->li_is_multi_value;
			if ($type == 'text') {
				$this->layoutItemsObj->li_is_poem = $obj->li_is_poem;
			}
			$this->layoutItemsObj->save(true);
			$obj->li_id = $this->layoutItemsObj->id;
		}

		$liId = ($this->layoutItemsObj->id) ? $this->layoutItemsObj->id : $obj->li_id;

		if($owned == 'template' && $obj->li_id && !$onlyTemplate) {
			//save texts and images
			if($type == 'text') {
				if(!$isFrontEnd && !$memoryListProductId) {

                    if($obj->li_id){
                        $this->textsObj->deleteByField('ppt_layout_item_id',intval($obj->li_id));
                    }
					$this->textsObj->id = null;
					$this->textsObj->ppt_product_page_id = $obj->ppt_product_page_id;
					$this->textsObj->ppt_layout_item_id = $liId;
					$this->textsObj->ppt_text = $obj->ppt_text;
					$this->textsObj->ppt_font_family = $obj->ppt_font_family;
					$this->textsObj->ppt_font_size = $obj->ppt_font_size;
					$this->textsObj->ppt_text_align = $obj->ppt_text_align;
					$this->textsObj->ppt_vertical_align = $obj->ppt_vertical_align;
					$this->textsObj->ppt_color = $obj->ppt_color;
					$this->textsObj->save();
				} else {
					$this->memoryTextsObj->id = null;
					$this->memoryTextsObj->mppt_memory_product_page_id  = $obj->ppt_product_page_id;
					$this->memoryTextsObj->mppt_layout_item_id = $liId;
					$this->memoryTextsObj->mppt_text = $obj->ppt_text;
					$this->memoryTextsObj->mppt_font_family = $obj->ppt_font_family;
					$this->memoryTextsObj->mppt_font_size = $obj->ppt_font_size;
					$this->memoryTextsObj->mppt_text_align = $obj->ppt_text_align;
					$this->memoryTextsObj->mppt_vertical_align = $obj->ppt_vertical_align;
					$this->memoryTextsObj->mppt_color = $obj->ppt_color;
					$this->memoryTextsObj->mppt_rotation = $obj->li_rotation;
					$this->memoryTextsObj->mppt_width = $obj->li_width;
					$this->memoryTextsObj->mppt_height = $obj->li_height;
					$this->memoryTextsObj->mppt_x = $obj->li_x;
					$this->memoryTextsObj->mppt_y = $obj->li_y;
					$this->memoryTextsObj->mppt_poem_id = $obj->ppt_poem_id;
					$this->memoryTextsObj->save();
				}
			} elseif($type == 'image') {

				if(!$isFrontEnd && !$memoryListProductId) {
                    if($obj->li_id){
                        $this->imagesObj->deleteByField('ppi_layout_item_id',intval($obj->li_id));
                    }
					$this->imagesObj->id = null;
					$this->imagesObj->ppi_product_page_id  = $obj->ppi_product_page_id;
					$this->imagesObj->ppi_layout_item_id = $liId;
					$this->imagesObj->ppi_photo_id = $obj->ppi_photo_id;
					$this->imagesObj->ppi_iw = $obj->ppi_iw;
					$this->imagesObj->ppi_ih = $obj->ppi_ih;
					$this->imagesObj->ppi_ir = $obj->ppi_ir;
					$this->imagesObj->ppi_ix = $obj->ppi_ix;
					$this->imagesObj->ppi_iy = $obj->ppi_iy;
					$this->imagesObj->ppi_image_filter = $obj->ppi_image_filter;
					$this->imagesObj->save();
				} else {
					$this->memoryImagesObj->id = null;
					$this->memoryImagesObj->mppi_memory_product_page_id = $obj->ppi_product_page_id;
					$this->memoryImagesObj->mppi_layout_item_id = $liId;
					$this->memoryImagesObj->mppi_photo_id = $obj->ppi_photo_id;
					$this->memoryImagesObj->mppi_iw = $obj->ppi_iw;
					$this->memoryImagesObj->mppi_ih = $obj->ppi_ih;
					$this->memoryImagesObj->mppi_ir = $obj->ppi_ir;
					$this->memoryImagesObj->mppi_ix = $obj->ppi_ix;
					$this->memoryImagesObj->mppi_iy = $obj->ppi_iy;
					$this->memoryImagesObj->mppi_image_filter = $obj->ppi_image_filter;
					$this->memoryImagesObj->mppi_rotation = $obj->li_rotation;
					$this->memoryImagesObj->mppi_width = $obj->li_width;
					$this->memoryImagesObj->mppi_height = $obj->li_height;
					$this->memoryImagesObj->mppi_x = $obj->li_x;
					$this->memoryImagesObj->mppi_y = $obj->li_y;
					$this->memoryImagesObj->save();

				}
			}
		}

		//if owned is design save texts and images
		if($owned == 'design' && !$isFrontEnd) {
			if ($type == 'text') {
				$this->designTextsObj->deleteByField('dt_layout_item_id',$this->layoutItemsObj->id,0);
				$this->designTextsObj->id = null;
				$this->designTextsObj->dt_layout_item_id = $this->layoutItemsObj->id;
				$this->designTextsObj->dt_text = $obj->ppt_text;
				$this->designTextsObj->dt_font_family = $obj->ppt_font_family;
				$this->designTextsObj->dt_font_size = $obj->ppt_font_size;
				$this->designTextsObj->dt_text_align = $obj->ppt_text_align;
				$this->designTextsObj->dt_vertical_align = $obj->ppt_vertical_align;
				$this->designTextsObj->dt_color = $obj->ppt_color;
				$this->designTextsObj->save();
			} elseif($type == 'image') {
				$this->designImagesObj->deleteByField('di_layout_item_id',$this->layoutItemsObj->id,0);
				$this->designImagesObj->id = null;
				$this->designImagesObj->di_layout_item_id = $this->layoutItemsObj->id;
				$this->designImagesObj->di_photo_id = $obj->ppi_photo_id;
				$this->designImagesObj->di_iw = $obj->ppi_iw;
				$this->designImagesObj->di_ih = $obj->ppi_ih;
				$this->designImagesObj->di_ir = $obj->ppi_ir;
				$this->designImagesObj->di_ix = $obj->ppi_ix;
				$this->designImagesObj->di_iy = $obj->ppi_iy;
				$this->designImagesObj->di_image_filter = $obj->ppi_image_filter;
				$this->designImagesObj->save();
			}
		}

		return $this->layoutItemsObj->id;
	}

	 /**
	  * @param $objTextsColor
	  * @param $designId
	  */
	 public function saveDesignLayoutTextsColor($objTextsColor, $designId) {
		 //delete current layout items
		 $this->textColorObj->deleteByField('pptc_design_id', $designId, 0);

		 foreach($objTextsColor as $objTextColor) {
			 //save products page text color
			 $this->saveItemTextColor($objTextColor, $designId);
		 }
	 }

	 public function saveItemTextColor($objTextColor, $designId){
		 $this->textColorObj->id = null;
		 $this->textColorObj->pptc_loyout_item_id = $objTextColor->li_id;
		 $this->textColorObj->pptc_design_id = $designId;
		 $this->textColorObj->pptc_color = $objTextColor->ppt_color;
		 $this->textColorObj->pptc_font_family = $objTextColor->ppt_font_family;
		 $this->textColorObj->pptc_font_size = $objTextColor->ppt_font_size;
		 $this->textColorObj->pptc_line_height = $objTextColor->ppt_line_height;
		 $this->textColorObj->pptc_text = $objTextColor->ppt_text;
		 $this->textColorObj->pptc_text_align = $objTextColor->ppt_text_align;
		 $this->textColorObj->pptc_vertical_align = $objTextColor->ppt_vertical_align;
		 $this->textColorObj->save();
	 }


	 /**
	  * @param $templateId
	  * @return int|string
	  */
	 public function removeTemplate($templateId) {
		//check where template is used
		$productsNumberUsed = $this->productsPages->getProductsUsedByTemplateId($templateId);
		$memoryProductsNumberUsed = $this->memoryProductsPagesObj->getMemoryProductsUsedByTemplateId($templateId);
		if(intval($productsNumberUsed) > 0 || intval($memoryProductsNumberUsed) > 0 ) {
			return "This template is used in " . intval($productsNumberUsed) . ' products and ' . intval($memoryProductsNumberUsed) . ' memory products';
		}

		//else delete template from system
		//first find all layout items for this template
		$liIds = $this->layoutItemsObj->getIdsByOwnerId($templateId, 'template');
		//find designs by template id
		$designs = $this->designObj->findAllByField('d_template_id', $templateId);
		 //list of designs Id
		$listDesigns = array();
		foreach($designs as $design) {
			$listDesigns[] = $design->id;
		}

		 if (count($liIds) > 0) {
			 //delete from texts and images
			 $this->textsObj->deleteByLiIds($liIds);
			 $this->imagesObj->deleteByLiIds($liIds);
			 $this->memoryTextsObj->deleteByLiIds($liIds);
			 $this->memoryImagesObj->deleteByLiIds($liIds);
			 $this->textColorObj->deleteByLiIds($liIds);
		 }
		 //delete designs galleries and photos
		 if(count($listDesigns) > 0) {
			 $listGalleries = $this->galleryObj->getGalleryByOwnerIdAndType($listDesigns);
			 $this->galleryObj->deleteByLiIds($listDesigns);
			 Db_Products_Photos::deleteByLiIds($listGalleries);
		 }

		$this->productsPages->deleteByField('pp_template_id', $templateId, 0);
		$this->memoryProductsPagesObj->deleteByField('mpp_memory_product_id', $templateId, 0);
		$this->layoutItemsObj->deleteByOwner($templateId, 'template');

		//delete designs
		//get designs list
		$designs = $this->designObj->getDesignsByTemplateId($templateId);
		if ($designs) {
			foreach ($designs as $design) {
				$liIds = $this->layoutItemsObj->getIdsByOwnerId($design['id'], 'design');
				$this->layoutItemsObj->deleteByField('pptc_design_id', $design['id'], 0);
				if (count($liIds) > 0) {
					$this->designTextsObj->deleteByLiIds($liIds);
					$this->designImagesObj->deleteByLiIds($liIds);
				}
				$this->layoutItemsObj->deleteByOwner($design['id'], 'design');
			}
			$this->designObj->deleteByField('d_template_id', $templateId, 0);
		}
		$this->templateObj->deleteByField('id',$templateId);
		return 1;
	}

	 /**
	  * @param $photoId
	  * @return string
	  */
	 public function deleteImage($photoId) {
		if($this->photosObj->deleteByField('id', $photoId)) {
			//@todo delete image
			return 'ok';
		}
		return 'error delete';
	}

	 /**
	  * @param $photoGalleryIdentifier
	  * @return array|bool
	  */
	public function getImages($photoGalleryIdentifier){
		return $this->galleryObj->getPhotosGalleryByMemoryListIdentifier($photoGalleryIdentifier);
	}

	 /**
	  * @param $memoryProductId
	  * @param $fileStream
	  * @return int|string
	  */
	 public function saveThumbnail($memoryProductId, $fileStream) {

		 $mlpId = Utils::memoryProductIdDecode($memoryProductId);
		 $memoryProductObj = new Db_Products_MemoryListProducts($mlpId);
		 if (!$memoryProductObj->objectArray->id) {
			 return 'Error memory product';
		 }

		 $microTime = microtime();
		 $name = md5($microTime).'_thumb.png';
		 $fileName = dirname(__FILE__) . $name;
		 $fileNameTh = dirname(__FILE__) . 'th_' . $name;

		 $file = fopen($fileName, 'w');
		 fwrite($file, $fileStream);
		 fclose($file);

		 $file = fopen($fileNameTh, 'w');
		 fwrite($file, $fileStream);
		 fclose($file);


		 $date = date('Y-m', time());
		 $path = PRODUCTS_USERS_THUMBNAILS_PATH . $date . DS;
		 Utils::mkDirIfNotExist($path);
		 $fileArray = array(
			'name' => $name,
			'tmp_name' => $fileName,
			'exists' => true
		 );
		 $imageSize = getimagesize($fileArray['tmp_name']);

		 $result = Utils::uploadFile($fileArray, $path, 1, conf('ALLOWED_EXTENSIONS'), false, 0, false, 0);

		 $fileArrayTh = array(
			'name' => 'th_' . $result['data']['name'],
			'tmp_name' => $fileNameTh,
			'exists' => true
		 );
		 $resultTh = Utils::uploadFile($fileArrayTh, $path, 1, conf('ALLOWED_EXTENSIONS'), false, 0, false, 0);
		 //return print_r($result, true);

		 if ($result['error'] == false) {

			 $photoObj = new Db_Products_Photos();
			 $photoObj->id = null;
			 $photoObj->ph_original = $fileArray['name'];
			 $photoObj->ph_name = $result['data']['name'];
			 $photoObj->ph_path = $result['data']['path'];
			 $photoObj->ph_ow = $imageSize[0];
			 $photoObj->ph_oh = $imageSize[1];
			 $photoObj->ph_resized = $resultTh['data']['name'];
			 $photoObj->ph_rw = $imageSize[0];
			 $photoObj->ph_rh = $imageSize[1];
			 if (!$photoObj->save()) {
				 return 'Error save photo in db';
			 }

			 $memoryProductObj->mlp_photo_id = $photoObj->id;
			 if (!$memoryProductObj->save()) {
				 return 'Error save in memory product';
			 }
			 return $memoryProductId;

		 } else {
			 return 0;
		 }

	 }

	 public function savePreviewPdf($memoryProductId, $fileStream) {
		 $mlpId = Utils::memoryProductIdDecode($memoryProductId);
		 $memoryProductObj = new Db_Products_MemoryListProducts($mlpId);
		 if (!$memoryProductObj->objectArray->id) {
			 return 'Error memory product';
		 }
		 $path = PRODUCTS_USERS_PDF_PREVIEW_PATH . date('Y-m', time()) . DS;
		 Utils::mkDirIfNotExist($path);
		 $fileName = $path.  md5($memoryProductId) . '.pdf';
		 $file = fopen($fileName, 'w');
		 fwrite($file, $fileStream);
		 fclose($file);
		 $link = str_replace(PUBLIC_RESOURCES_PATH, '', $fileName);
		 $memoryProductObj->mlp_preview_link = $link;
		 $memoryProductObj->save();

		 return self::$PROJECT['pr_resources_'.conf('ENVIRONMENT')] . $link;
	 }

	 /**
	  * @param $get
	  * @param $files
	  * @return bool|string
	  */
	public function uploadPhoto($get /*= array('type' => 'user', 'designID' => 0, 'memoryIdentifier' => '1')*/, $files) {
		//return $get['name'];
		switch($get['type']) {
			case 'default' :
				$imagePtah = PRODUCTS_PHOTOS_DEFAULT_PATH;
				break;
			case 'user' :
				$imagePtah = PRODUCTS_PHOTOS_USERS_PATH;
				break;
			case 'design' :
				$imagePtah = PRODUCTS_PHOTOS_DESIGNS_PATH;
				break;
			default:
				$imagePtah = PRODUCTS_PHOTOS_DEFAULT_PATH;
				break;

		}

		$galleryInfo = $this->memoryListObj->findByField('ml_memory_identifier', $get['memoryIdentifier']);

		if($galleryInfo->ml_gallery_id && $get['type'] != 'design') {
			 $galleryId = $galleryInfo->ml_gallery_id;
		} else {

			if( $get['type'] != 'design') {
				//Save gallery
				$this->galleryObj->id = null;
				$this->galleryObj->pg_gallery_type = $get['type'];
				$this->galleryObj->pg_owner_id = $get['designID'];
				$this->galleryObj->pg_user_id = (isset(self::$USER['id']) ? self::$USER['id'] : '');
				$this->galleryObj->save(true);
				$galleryId = $this->galleryObj->id;

				//Save Memory list
				$this->memoryListObj->id = null;
				$this->memoryListObj->ml_memory_identifier = $get['memoryIdentifier'];
				$this->memoryListObj->ml_gallery_id = $galleryId;
				$this->memoryListObj->ml_project_id = (isset(self::$PROJECT['id']) ? self::$PROJECT['id'] : '');
				$this->memoryListObj->save(true);
			} else {
				$galleryInfo = $this->galleryObj->findByFields(array('pg_owner_id' => $get['designID'],
																		'pg_gallery_type' => $get['type']));

				$this->galleryObj->id = (isset($galleryInfo->id) ? $galleryInfo->id : null);
				$this->galleryObj->pg_gallery_type = $get['type'];
				$this->galleryObj->pg_owner_id = $get['designID'];
				$this->galleryObj->save(true);
				$galleryId = $this->galleryObj->id;
			}
		}

		$arrayFile = (!empty($files['Filedata']) ? $files['Filedata'] : null );

		$allowedExtensions = conf('ALLOWED_EXTENSIONS');
		$resultUpload= Utils::uploadFile($arrayFile, $imagePtah, $galleryId, $allowedExtensions['default'], false, 0, true);
		if ($resultUpload['error']) {
		 	return $resultUpload['message'];
		} else {
			if($get['type'] != 'design') {
				//save memory list
				$this->memoryListObj->id = null;
				$this->memoryListObj->ml_memory_identifier = isset($get['memoryIdentifier']) ? $get['memoryIdentifier'] : '';
				$this->memoryListObj->ml_gallery_id = $galleryId;
				$this->memoryListObj->ml_project_id = self::$PROJECT['id'];
				$this->memoryListObj->save(true);
			}
			$env = conf('ENVIRONMENT');

			$photo = $resultUpload['data'];
			$photo['ph_original'] = self::$PROJECT['pr_resources_'. $env] . $photo['ph_path'] . $photo['ph_original'];
			$photo['ph_resized'] = self::$PROJECT['pr_resources_'. $env] . $photo['ph_path'] . $photo['ph_resized'];
			if(isset($get['ajax']) && $get['ajax'] == true) {
				return $photo;
			} else {
				self::$TPL->assign('photo', $photo);
				return self::$TPL->display('xml_flash_photo_return', true);
			}
		}

		return true;

	}

	public function getSizes(){

		$sizes = $this->sizesObj->findAllArray();
		$sizesReturn =  array();

		foreach($sizes as $size) {
			$sizeObj =  new SizeConf();
			$sizeObj->id = $size['id'];
			$sizeObj->s_name = $size['s_name'];
			$sizeObj->s_width = $size['s_width'];
			$sizeObj->s_height = $size['s_height'];
			$sizeObj->s_orientation = $size['s_orientation'];
			$sizeObj->s_face_number = $size['s_face_number'];
			$sizesReturn[] = $sizeObj;
		}

		return $sizesReturn;
	}

	 /**
	  * @param $sizeId
	  * @return ApplicationConf
	  */
	 public function getDataBySizeId($sizeId) {
		 //Instance of Application Config for Flash
		 $applicationData =  new ApplicationConf();

		 $allTemplates = $this->getFlashTemplates($sizeId, true);
		 $allDesigns = $this->getDesigns();

		 $designsObj = array();

		 foreach($allTemplates as $template) {
			 foreach($allDesigns as $templateIdKey ) {
				 foreach($templateIdKey as $themeKey => $design) {
					if($design->d_template_id == $template->id) {
						$designsObj[$applicationData->arrayKeysPrefix.$template->id][$applicationData->arrayKeysPrefix.$design->d_theme_id] = $design;
					}
				 }
			 }
		 }

		 $applicationData->themes = $this->getThemes();
		 $applicationData->templates = $allTemplates;
		 $applicationData->designs = $designsObj;
		 $designsImages = $this->galleryObj->getGalleryImagesByType('design');
		 $galleryPhotosArray = array();
		 if ($designsImages) {
			foreach ($designsImages as $photoDesign) {
				$galleryImageConfigObj = new GalleryImageConf();
				$galleryImageConfigObj->id = $photoDesign->id;
				$galleryImageConfigObj->ph_gallery_id = $photoDesign->ph_gallery_id;
				$galleryImageConfigObj->ph_original = $photoDesign->ph_original;
				$galleryImageConfigObj->ph_name = $photoDesign->ph_name;
				$galleryImageConfigObj->ph_path = $photoDesign->ph_path;
				$galleryImageConfigObj->ph_ow = $photoDesign->ph_ow;
				$galleryImageConfigObj->ph_oh = $photoDesign->ph_oh;
				$galleryImageConfigObj->ph_resized = $photoDesign->ph_resized;
				$galleryImageConfigObj->ph_rw = $photoDesign->ph_rw;
				$galleryImageConfigObj->ph_rh = $photoDesign->ph_rh;
				$galleryPhotosArray[$applicationData->arrayKeysPrefix . $photoDesign->pg_owner_id][$applicationData->arrayKeysPrefix . $photoDesign->photo_id] = $galleryImageConfigObj;
			}
		 }
		 $applicationData->designsImages = $galleryPhotosArray;
		 $applicationData->urlFonts = self::$PROJECT['pr_resources_'.conf('ENVIRONMENT')] . str_replace(PUBLIC_RESOURCES_PATH, '', PRODUCTS_FONTS_PATH);
		 return $applicationData;
	 }

	 public function getDesignsImages($designs) {

		 $applicationData =  new ApplicationConf();

		 $designsId = array();
		 foreach($designs as $templateId => $allDesigns) {
			 foreach($allDesigns as $design) {
				  $designsId[] = $design->id;
			 }
		 }
		 $designsImages = $this->galleryObj->getDesignsImages($designsId);

		 $galleryPhotosArray = array();
		 if ($designsImages) {
			 foreach ($designsImages as $photoDesign) {
				 $galleryImageConfigObj = new GalleryImageConf();
				 $galleryImageConfigObj->id = $photoDesign->id;
				 $galleryImageConfigObj->ph_gallery_id = $photoDesign->ph_gallery_id;
				 $galleryImageConfigObj->ph_original = $photoDesign->ph_original;
				 $galleryImageConfigObj->ph_name = $photoDesign->ph_name;
				 $galleryImageConfigObj->ph_path = $photoDesign->ph_path;
				 $galleryImageConfigObj->ph_ow = $photoDesign->ph_ow;
				 $galleryImageConfigObj->ph_oh = $photoDesign->ph_oh;
				 $galleryImageConfigObj->ph_resized = $photoDesign->ph_resized;
				 $galleryImageConfigObj->ph_rw = $photoDesign->ph_rw;
				 $galleryImageConfigObj->ph_rh = $photoDesign->ph_rh;
				 $galleryPhotosArray[$applicationData->arrayKeysPrefix . $photoDesign->pg_owner_id][$applicationData->arrayKeysPrefix . $photoDesign->photo_id] = $galleryImageConfigObj;
			 }
			 return $galleryPhotosArray;
		 } else {
			 return false;
		 }
	 }

	public function saveMultiValue() {
		$fileName = ROOT_PATH . 'public/static/common/flash/xls/use_file.xls';
		$xlsMultiValue = array();
		$objPHPExcel = PHPExcel_IOFactory::load($fileName);
		foreach ($objPHPExcel->setActiveSheetIndex(0)->getRowIterator() as $row) {
			$cellIterator = $row->getCellIterator();
			$cellIterator->setIterateOnlyExistingCells(false);
			foreach ($cellIterator as $cell) {
				if (!is_null($cell)) {
					$xlsMultiValue[] = $cell->getValue();
				}
			}
		}
		return $xlsMultiValue;
	}

	function saveProductThumbnail($fileStream, $productId, $themeId, $sizes, $fileExtension) {
		$microTime = microtime(true);
		$name = md5($microTime) . '.' . $fileExtension;
		$fileName = dirname(__FILE__) . 'hq_'.$name;
		$file = fopen($fileName, 'w');
		fwrite($file, $fileStream);
		fclose($file);

		$gallery = Db_Products_PhotosGalleries::findByFields(array(
			'pg_owner_id' => $productId,
			'pg_gallery_type' => 'product'
		));

		$path = PRODUCTS_PHOTOS_PRODUCT_PATH . $productId . DS;
		Utils::mkDirIfNotExist($path);
		$fileArray = array();

		$fileArray['original'] = array(
			'name' => str_replace('.'.$fileExtension, '', 'hq_'.$productId . '_' . str_replace('.', '', $microTime)),
			'tmp_name' => $fileName,
			'exists' => true
		);

		$resizeNameBig = $name;
		$resizeNameSmall = 'th_' . $name;
		$image = new Imagick($fileName);

		$image->thumbnailImage($sizes['big'][0], $sizes['big'][1]);
		$image->writeImage(dirname(__FILE__) . $name);
		$imageResSizeBig =  getimagesize(dirname(__FILE__) . $resizeNameBig);

		$image->thumbnailImage($sizes['small'][0], $sizes['small'][1]);
		$image->writeImage(dirname(__FILE__) . $resizeNameSmall);
		$imageResSizeSmall =  getimagesize(dirname(__FILE__) . $resizeNameSmall);

		$image->clear();
		$image->destroy();

		$fileArray['big'] = array(
			'name' => str_replace('.'.$fileExtension, '', $productId . '_' . str_replace('.', '', $microTime)),
			'tmp_name' => dirname(__FILE__) . $resizeNameBig,
			'exists' => true
		);

		$fileArray['small'] = array(
			'name' => str_replace('.'.$fileExtension, '', 'th_' . $productId . '_' . str_replace('.', '', $microTime)),
			'tmp_name' => dirname(__FILE__) . $resizeNameSmall,
			'exists' => true
		);

		$resultOriginalFileUpload = Utils::uploadFile($fileArray['original'], $path, 1, conf('ALLOWED_EXTENSIONS'), true, 0, false, 0);
		$resultBigUpload = Utils::uploadFile($fileArray['big'], $path, 1, conf('ALLOWED_EXTENSIONS'), true, 0, false, 0);
		$resultSmallUpload = Utils::uploadFile($fileArray['small'], $path, 1, conf('ALLOWED_EXTENSIONS'), true, 0, false, 0);

		if ($resultOriginalFileUpload['error'] == false && $resultBigUpload['error'] == false && $resultSmallUpload['error'] == false) {
			$photoObj = new Db_Products_Photos();
			$photoObj->id = null;
			$photoObj->ph_gallery_id = $gallery->id;
			$photoObj->ph_name_hq = $resultOriginalFileUpload['data']['name'];
			$photoObj->ph_path = $resultOriginalFileUpload['data']['path'];
			$photoObj->ph_original = $resultBigUpload['data']['name'];
			$photoObj->ph_name = $resultBigUpload['data']['name'];
			$photoObj->ph_ow = $imageResSizeBig[0];
			$photoObj->ph_oh = $imageResSizeBig[1];
			$photoObj->ph_resized = $resultSmallUpload['data']['name'];
			$photoObj->ph_rw = $imageResSizeSmall[0];
			$photoObj->ph_rh = $imageResSizeSmall[1];
			if (!$photoObj->save()) {
				return 'Error save photo in db';
			}

			$productsThemePhoto = array(array(
				'pt_product_id' => $productId,
				'pt_theme_id' => $themeId,
				'pt_photo_id' => $photoObj->id
			));
			self::$DB->insertBatch(TAB_PRODUCT_THEME_PHOTOS, $productsThemePhoto, true);

			return true;
		} else {
			return false;
		}
 	}



	public function saveTextsImages() {
//		$this->textsObj->id = $textObj->id;
//		$this->textsObj->ppt_layout_item_id = $layoutId;
//		$this->textsObj->ppt_text = $textObj->ppt_text;
//		$this->textsObj->ppt_font_family = $textObj->ppt_font_family;
//		$this->textsObj->ppt_font_size = $textObj->ppt_font_size;
//		$this->textsObj->ppt_text_align = $textObj->ppt_text_align;
//		$this->textsObj->ppt_vertical_align = $textObj->ppt_vertical_align;
//		$this->textsObj->ppt_color = $textObj->ppt_color;
//		$this->textsObj->save();
//
//		$this->imagesObj->id = $imageObj->id;
//		$this->imagesObj->ppi_layout_item_id = $layoutId;
//		$this->imagesObj->ppi_photo_id = $imageObj->ppi__photo_id;
//		$this->imagesObj->ppi_iw = $imageObj->ppi_iw;
//		$this->imagesObj->ppi_ih = $imageObj->ppi_ih;
//		$this->imagesObj->ppi_ir = $imageObj->ppi_ir;
//		$this->imagesObj->ppi_ix = $imageObj->ppi_x;
//		$this->imagesObj->ppi_iy = $imageObj->ppi_y;
//		$this->imagesObj->ppi_image_filter = $imageObj->ppi_image_filter;
//		$this->imagesObj->save();
	}

 }
